$(function () {
    var myChart = echarts.init(document.getElementById("network"));
    var color_pool = ['#2980B9', '#E74C3C', '#48C9B0', '#F7DC6F', '#B9770E', '#8E44AD', '#797D7F', '#7B241C', '#EC7063', '#884EA0',
        '#AF7AC5', '#5DADE2', '#1ABC9C', '#27AE60', '#F39C12', '#EDBB99', '#F5B7B1', '#FAD7A0']
    var max_visual_nodes = 70;
    var classification_chart, pca_chart, kmeans_chart;
    classification_chart = echarts.init(document.getElementById("classification"));
    pca_chart = echarts.init(document.getElementById("pca"));
    kmeans_chart = echarts.init(document.getElementById("kmeans"));
    var net, task_id, labels;
    var edges = [], categories = [], legend = [];


    function visual_graph(graph, data_name) {
        net = JSON.parse(JSON.stringify(graph));
        myChart.hideLoading();
        labels = graph['label'];
        for (var i = 0; i < graph.nodes.length; i++) {
            graph.nodes[i].category = labels[graph.nodes[i].name][1];
            graph.nodes[i].name = graph.nodes[i].name.toString();
        }
        for (var j = 0; j < graph.edges.length; j++) {
            edges.push([graph.edges[j].source, graph.edges[j].target]);
            graph.edges[j].source = graph.edges[j].source.toString();
            graph.edges[j].target = graph.edges[j].target.toString();
        }
        if (labels) {
            switch (data_name) {
                case 'xbrazil-flights': {
                    let leibie = ["航班1", "航班2", "航班3", "航班4",]
                    for (var i = 0; i < graph.classes; i++) {
                        categories[i] = {
                            name: leibie[i]
                        };
                        legend[i] = {
                            name: leibie[i]
                        };
                    }
                    break;
                }
                case 'xbarbell': {
                    let leibie = ["杠铃节点1", "杠铃节点2", "杠铃节点3", "杠铃节点4", "杠铃节点5", "杠铃节点6", "杠铃节点7"]
                    for (var i = 0; i < graph.classes; i++) {
                        categories[i] = {
                            name: leibie[i]
                        };
                        legend[i] = {
                            name: leibie[i]
                        };
                    }
                    break;
                }
                case 'xeurope-flights': {
                    let leibie = ["航班1", "航班2", "航班3", "航班4",]
                    for (var i = 0; i < graph.classes; i++) {
                        categories[i] = {
                            name: leibie[i]
                        };
                        legend[i] = {
                            name: leibie[i]
                        };
                    }
                    break;
                }
                case 'xhospital': {
                    let leibie = ["医生", "护士", "病人", "护工",]
                    for (var i = 0; i < graph.classes; i++) {
                        categories[i] = {
                            name: leibie[i]
                        };
                        legend[i] = {
                            name: leibie[i]
                        };
                    }
                    break;
                }
                default: {
                    for (var i = 0; i < graph.classes; i++) {
                        categories[i] = {
                            name: '类别' + (i + 1)
                        };
                        legend[i] = {
                            name: '类别' + (i + 1)
                        };
                    }
                    break;
                }
            }
        }
    }
    var option = {
        tooltip: {},
        // backgroundColor: '#eee',
        color: color_pool,
        legend: {
            data: legend,
        },
        series: [{
            type: 'graph',
            layout: 'force',
            symbolSize: 12,
            roam: true,
            force: { //力引导图基本配置
                repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                layoutAnimation: false
                //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
            },
            zoom: 1,
            data: graph.nodes.slice(0, max_visual_nodes),
            links: graph.edges,
            categories: categories,
            label: {
                normal: {
                    show: false,
                    textStyle: {
                        fontSize: 10
                    },
                }
            },
            edgeLabel: {
                show: true,
                normal: {
                    textStyle: {
                        fontSize: 20
                    }
                }
            },
            normal: {
                width: 0.3,
                curveness: 0.3,
                opacity: 0.7
            }
        }]
    };
    myChart.setOption(option);


    const socket = io('/status', {});
    socket.on('embed_log', function (res) {
        $("#algoRes").append(res + '<br/>');
        if (res.indexOf("Run classification") >= 0) {
            classification_chart.resize();
            classification_chart.showLoading();
        }
        if (res.indexOf("Run PCA") >= 0) {
            pca_chart.resize();
            pca_chart.showLoading();
        }
        if (res.indexOf("Run K-Means") >= 0) {
            kmeans_chart.resize();
            kmeans_chart.showLoading();
        }
    });
    socket.on('classification', function (data) {
        var option = {
            legend: {
                data: ['Micro-F1', 'Macro-F1'],
            },
            xAxis: {
                type: 'value',
            },
            yAxis: {
                type: 'value',
                min: data['f1-macro'][0][1] - 0.1 >= 0 ? data['f1-macro'][0][1] - 0.1 : 0,
                max: data['f1-micro'][8][1] + 0.1 <= 1 ? data['f1-micro'][8][1] + 0.1 : 1,
            },
            series: [
                {
                    name: 'Micro-F1',
                    type: 'line',
                    data: data['f1-micro']
                },
                {
                    name: 'Macro-F1',
                    type: 'line',
                    data: data['f1-macro']
                },
            ]
        };
        classification_chart.hideLoading();
        classification_chart.setOption(option);
    });
    socket.on('pca', function (data) {
        var pca_data = JSON.parse(JSON.stringify(data));
        var option = {
            color: color_pool,
            xAxis: {
                show: false,
                type: 'value'
            },
            yAxis: {
                show: false
            },
            series: [
                {
                    type: 'scatter',
                    name: 'pca',
                    data: pca_data.slice(0, 500),
                    itemStyle: {
                        color: function (params) {
                            return color_pool[labels[params.dataIndex][1]];
                        }
                    }
                }
            ]
        };
        pca_chart.hideLoading();
        pca_chart.setOption(option);
    });
    socket.on('k-means', function (data) {
        kmeans_chart.hideLoading();
        for (var i = 0; i < net.nodes.length; i++) {
            net.nodes[i].category = data[net.nodes[i].name];
        }
        var option = {
            tooltip: {},
            color: color_pool,
            legend: {
                data: legend,
            },
            series: [{
                type: 'graph',
                layout: 'force',
                symbolSize: 12,
                roam: true,
                force: { //力引导图基本配置
                    repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                    gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                    edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                    layoutAnimation: false
                    //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                },
                data: net.nodes.slice(0, 70),
                links: net.edges,
                categories: categories,
                label: {
                    normal: {
                        show: false,
                    }
                },
                normal: {
                    width: 0.3,
                    curveness: 0.3,
                    opacity: 0.7
                }
            }]
        };
        kmeans_chart.setOption(option);
    });

    layui.config({ base: '/static/js/layui/lay/modules/' })
        .use(['table', 'dropdown', 'element', 'upload'], function () {
            var table = layui.table;
            var dropdown = layui.dropdown;
            var element = layui.element;
            var upload = layui.upload;

            upload.render({
                elem: '#graph', //绑定元素
                accept: 'file',
                url: '/networkapi/upload',
                auto: false,
                bindAction: '#upload',
                number: 2,
                multiple: true,
                done: function (res, index, upload) {
                    if (res.code !== 0) {
                        layer.alert(res.msg, { icon: 2 });
                    }
                },
                allDone: function (obj) {
                    window.location.reload();
                }
            });

            table.render({
                elem: '#test',
                url: '/networkapi/statistic_info',
                where: { xhrFields: { withCredentials: true }, crossDomain: true },
                cellMinWidth: 80,//全局定义常规单元格的最小宽度，layui 2.2.1 新增
                cols: [[
                    { field: 'name', width: 160, sort: true, fixed: true, title: '数据集名称' },
                    { field: 'nodes', width: 80, title: '节点数' },
                    { field: 'edges', width: 80, sort: true, title: '边数' },
                    { field: 'density', width: 180, title: '网络密度' },
                    { field: 'degree_max', width: 80, title: '最大度' },
                    { field: 'degree_min', width: 80, sort: true, title: '最小度' },
                    { field: 'degree_avg', width: 180, title: '平均度' },
                    { field: 'clustering', width: 180, sort: true, title: '平均聚集系数' },
                    { fixed: 'right', width: 178, align: 'center', toolbar: '#barDemo' }
                ]],
                done: function (res) {
                    dropdown.suite();
                    dropdown.onFilter('algo', function (event) {
                        $.ajax({
                            url: '/networkapi/args',
                            type: 'get',
                            data: {
                                'method': event
                            },
                            async: true,
                            success: function (data) {
                                $('#algoIntro').empty();
                                for (var key in data) {
                                    $('#algoIntro').append(
                                        $(
                                            "<div class='layui-col-md3'>" +
                                            "<form class='layui-form layui-form-pane' action=''>" +
                                            "<div class='layui-form-item'>" +
                                            "<label class='layui-form-label'>" + key +
                                            "</label>" +
                                            "<input class='layui-input' type='text' class='form-control' name='role' id='" + key +
                                            "' value='" + data[key] + "'>" +
                                            "</div>" +
                                            "</form>" +
                                            "</div>")
                                    );
                                }
                                $('#algoIntro').append($("<div class='layui-col-md3'>" +
                                    "<button class='layui-btn' id='exec'>运行</button>" +
                                    "</div>"));
                                $("#exec").on('click', function () {
                                    var args = {};
                                    $("#algoRes").empty();
                                    classification_chart.clear();
                                    kmeans_chart.clear();
                                    pca_chart.clear();
                                    task_id = new Date().getTime();
                                    $("input[name=role]").each(function () {
                                        args[$(this).attr('id')] = $(this).val();
                                    });
                                    $.ajax({
                                        url: '/networkapi/role',
                                        type: 'post',
                                        data: JSON.stringify({
                                            data: edges,
                                            task_id: task_id
                                        }),
                                        success: function (data) {
                                            var post_data = {
                                                method: event,
                                                args: args,
                                                task_id: task_id
                                            };
                                            if (labels.length > 0) {
                                                post_data['label'] = labels;
                                            }
                                            socket.emit('status', post_data);
                                        }
                                    });
                                })
                            }
                        })
                    });
                }
            });
            //监听工具条
            table.on('tool', function (obj) {
                var data = obj.data;
                if (obj.event === 'detail') {
                    myChart.showLoading();
                    $.ajax({
                        url: '/networkapi/dataset',
                        type: 'get',
                        data: {
                            dataset: data.name
                        },
                        success: function (graph) {
                            visual_graph(graph, data.name);
                        }
                    });
                }
            });
        });

});